//
//  BaseLoginController.swift
//  通用登陆方法
//
//  Created by smile on 2019/4/8.
//  Copyright © 2019 ixuea. All rights reserved.
//

import UIKit

class BaseLoginController: BaseTitleController {


    /// 登陆
    ///
    /// - Parameter api: <#api description#>
    func login(phone:String?=nil,email:String?=nil,password:String?=nil,qq_id:String?=nil,weibo_id:String?=nil) {
        Api.shared
            .login(phone: phone, email: email, password: password, qq_id: qq_id, weibo_id: weibo_id)
            .subscribe({ data in
                //有些接口可能返回空
                //也表示成功
                //但对于登录登陆，返回空肯定是有问题
                //所以这里可以直接解包
                self.onLoginSucces(data!.data!)
                
                //登陆聊天服务
                let id=StringUtil.processUserId(data!.data!.user)
                JMSGUser.login(withUsername: id, password: id, completionHandler: { (data, error) in
                    
                    if let error = error {
                        print("RegisterController message login failed:\(error)")
                    }else{
                        print("RegisterController message login success")
                    }
                    
                })
                
                //统计登陆成功事件
                AnalysisUtil.onLogin(success: true,phone: phone,email: email,qq_id: qq_id,weibo_id: weibo_id)
            }) { (baseResponse, error) -> Bool in
                //统计登陆失败事件
                //像无网络
                //用户名密码格式不正确这些就不统计了
                //当然真实项目中可能也需要统计
                AnalysisUtil.onLogin(success: false,phone: phone,email: email,qq_id: qq_id,weibo_id: weibo_id)
                
                //让框架自动处理错误
                return false
        }.disposed(by: disposeBag)
        
        
    }

    
    func onLoginSucces(_ data:Session) {
        //登陆成功
        
        //保存登陆信息
        PreferenceUtil.setUserId(data.user)
        PreferenceUtil.setUserToken(data.session)

        //调用AppDelegate中的方法，进入首页
        AppDelegate.shared.toHome()
        
    }
}
